$(function(){
	
	
	var orderInfoAjaxOperator = new OrderInfoAjaxOperator();
	var orderInfoRenderer = new OrderInfoRenderer();
	var dateFormatUtil = new DateFormatUtil();
    var merchantName = '';
    var pagePath = $("#pagePath").val();
    var orderInfoId = '';
    var customerId = $("#hidden_customer_id").val();

	    // 该对象负责 前后台 数据的交互
    function OrderInfoAjaxOperator(){
        var obj = {};
        
        //加载后台的 orderItems
        obj.loadOrderInfoById = function(orderInfoId, onSuccess){
            $.ajax({
                url: "../id/"+orderInfoId,
                type: "GET",
                dataType: "json"
            }).done(function(items){
                onSuccess(items);  ////真正执行的回调函数： 刷新购物车面板
            });    
        };


        //点击了 购物车 checkout 按钮
        obj.chechOutOrderInfo = function(){
            $.ajax({
                url: "../orderInfos",
                type: "GET",
                dataType: "json"
            }).done(function(){

            });
        };


         obj.add = function(json){
                $.ajax({
                    type:"POST",
                    url:pagePath+"/commentary",
                    data:json,
                    contentType:"application/json",
                    dataType: "json"
                }).done(function(msg){
                    if(msg==null){
                        alert("服务器状态不佳");
                    }else{
                        alert("评论成功");
                    }
                });
            };

        obj.addCompliaint = function(json){
             $.ajax({
                type:"POST",
                url:pagePath+"/complaintInfo",
                data:JSON.stringify(json),
                contentType:"application/json",
                dataType: "json"
            }).done(function(msg){
                if(msg != null){
                    alert("投诉已发送！");
                    $("#orderInfoDetailModel").modal("hide");
                    window.location = pagePath+"/orderInfo/customerId/"+customerId;
                }else{
                    alert("服务器出错，请稍后重试");
                }
            });
        }

        obj.confirmReceiveOrderInfo = function(){
            $.ajax({

            })
        }

        return obj;
    };
	



    //评论内容对象
        function Evaluate(){
            var grade;
            var merchantName;
            var commentary;
        }

        function Complait(){
            var orderInfoId;
            var merchantName;
            var reason;
        }

        //封装文字提示函数  
        function indexText(i) {
            switch (i) {
            case 0:
                return '非常不满意';
            case 1:
                return '不满意';
            case 2:
                return '一般';
            case 3:
                return '满意';
            case 4:
                return '非常满意';
            }
        }
        





    //OrderInfo 的渲染器
	function OrderInfoRenderer(){
		var obj = {};

		obj.showDetailOrderInfo = function(orderDetail){
			var model = $("#orderInfoDetailModel");
            model.find("table").empty();
            orderInfoId = orderDetail.id;
            model.find("h4").eq(0).children().eq(1).text(orderDetail.id);
            model.find("h4").eq(1).children().eq(1).text(orderDetail.customer.username);
            model.find("h4").eq(2).children().eq(1).text(dateFormatUtil.formatDate(orderDetail.orderDate));



            model.find("h4").eq(5).children().eq(1).text(orderDetail.receiverInfo.phone);
            model.find("h4").eq(6).children().eq(1).text(orderDetail.receiverInfo.address );
            model.find("h4").eq(7).children().eq(1).text(orderDetail.orderStatus);
            let table = "<tr><td></td><td></td></tr>";
            let totalPrice = 0;
            orderDetail.items.forEach((item,index)=>{
                let table1=$(table);
                table1.children().eq(0).text(item.food.name);
                table1.children().eq(1).text("   ×  "+item.total);
                totalPrice += item.food.price*item.total;
                model.find("table").append(table1);
            })
            model.find("h4").eq(4).children().eq(1).text(totalPrice);
            // alert("orderDetail.orderStatus "+orderDetail.orderStatus);
            if($.trim(orderDetail.orderStatus) == "COMPLETED"){

                 let btn1 = model.find("button[name='button1']");
                if(orderDetail.isComplaint == 1){
                    btn1.text("已投诉").addClass("btn btn-success");

                }else{
                    btn1.text("投诉").addClass("btn btn-warning");;
                    btn1.on("click",function(){
                        $("input[name='complaint_to_merchantName']").val(merchantName);
                        $("#myComplaintModal").modal('show');

                    })
                }   
                
            }else{
                 let btn1 = model.find("button[name='button1']");
                 $(btn1).hide();
            }

		}

		return obj;
	}
	
	//时间格式化工具
	function DateFormatUtil(){
		var obj = {};

		obj.formatDate = function(time){
			let newDate = new Date();
			newDate.setTime(time);
			let fmtDate = newDate.getFullYear() +"年" + eval(newDate.getMonth()+1) +"月" +
						  newDate.getDate() +"日";
			return fmtDate;
		}
		return obj;
	}

	/*各种监听器*/
	$("button[name='orderInfo_detail_in_myhome']").on("click", function(event){

		var orderInfoId = $(event.target).prev().val(); //拿到Id
        merchantName = $(event.target).prev().attr("name"); //拿到商家名字
		var orderInfo =  orderInfoAjaxOperator.loadOrderInfoById(orderInfoId, orderInfoRenderer.showDetailOrderInfo); //拿到数据
	}); 

// 点击评论按钮
    $("button[name='orderInfo_comment_in_myhome']").on("click", function(event){
        merchantName = $(event.target).prev().val(); //拿到商家名字
    }); 

    


    $('#evaluate_btn').click(
                    function() {
                    
                        var text = $('.score').text();
                        if(text == ''){
                            alert('请完成评分再提交！');
                            throw "请完成评分再提交！";
                        }
                        
                        var reg=/[\u4E00-\u9FA5]/g;
                        var grade = text.replace(reg,'').replace("/","").replace("(","").replace(")","").trim();
                        var merchantId = $("#merchantId").val();
                        var commentary = $("#commentary").val().trim();
                        if(commentary==''){
                            alert("你没有填写评价哦");
                            throw "你没有填写评价哦";
                        }
                        var e = new Evaluate();
                        e.grade = grade;
                        /* e.merchantId = merchantId; */
                        e.merchantName = merchantName;
                        e.commentary = commentary;
                        orderInfoAjaxOperator.add(JSON.stringify(e));
                       
                        $('#myEvluateModal').modal('hide');
                    });



    $("#orderInfoList").on("click", function(event){
        if(event.target.id == "confirm_receive_btn"){
            var orderInfoId = $(event.target).prev().val();
            var r = confirm("确认收货吗？");
            if(r == true){
                window.location=pagePath + "/orderInfo/"+orderInfoId;
            }
        }
    });



    /*harry*/

var tip_text = '', $parent = {};
            $(".glyphicon")
                    .bind(
                            {
                                mouseout : function() {
                                    $parent.children('.extra').remove();
                                    var score = $parent.siblings('.score')
                                            .html();
                                    if (score) {//有星星选中时  
                                        $parent.children(
                                                ":lt(" + parseInt(score) + ")")
                                                .removeClass(
                                                        'glyphicon-star-empty')
                                                .addClass('glyphicon-star');//PS:此处应该加上parseInt进行整型转换，否则会没有效果  
                                        $parent
                                                .children(
                                                        ":gt("
                                                                + eval(parseInt(score) - 1)
                                                                + ")")
                                                .removeClass('glyphicon-star')
                                                .addClass(
                                                        'glyphicon-star-empty');//PS:此处要记得加eval，进行js计算，不然会报“jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: NaN)”的错误  
                                    } else {
                                        $(this).prevAll().andSelf()
                                                .removeClass('glyphicon-star')
                                                .addClass(
                                                        'glyphicon-star-empty');
                                    }
                                },
                                mouseover : function() {
                                    $parent = $(this).parent();//把父节点存放起来  
                                    var score = $parent.siblings('.score')
                                            .html();
                                    $parent
                                            .append('<span class="extra dot-left"></span><span class="extra tip"></span>');//添加提示框  
                                    tip_text = indexText($(this).index());//得到相应的文字提示  
                                    $(this).siblings('.tip').html(tip_text);//显示文字提示  
                                    $(this).prevAll().andSelf().removeClass(
                                            'glyphicon-star-empty').addClass(
                                            'glyphicon-star');
                                    if (score) {//当有星星选中时，为了解决鼠标移到选中星星的的前面星星时的小bug，此时会出现前面星星鼠标滑动时，星星颜色不变化现象  
                                        $(this).nextAll().not('.extra')
                                                .removeClass('glyphicon-star')
                                                .addClass(
                                                        'glyphicon-star-empty');
                                    }
                                },
                                click : function() {
                                    var score = $(this).index() + 1;
                                    $parent.siblings('.score').html(
                                            score + '(' + tip_text + ')');
                                    $(this).prevAll().andSelf().removeClass(
                                            'glyphicon-star-empty').addClass(
                                            'glyphicon-star');
                                }
                            });



                    /*投诉用*/
                    // $("#complait").on("click",function(){
                    //        // $("button[name='orderInfo_detail_in_myhome']").on("click", function(event){
                          
                    //         $("#complaint_to_merchantName")
                    //     });
                        
                        $("#send_complaint_info").on("click",function(){
                            var c = new Complait();
                            c.merchantName = merchantName;
                            c.reason = $("#complait_reason").val().trim();
                            c.orderInfoId = orderInfoId;
                            $("#myComplaintModal").modal("hide");
                            if(c.reason.length > 50){
                                alert("理由超出长度哦！");
                                
                            }else if(c.reason.length == 0){
                                alert("投诉理由不能为空哦");
                            }else{
                               orderInfoAjaxOperator.addCompliaint(c);
                            }
                            
                        });
                        

});